<?php
    @header("Content-Type:text/html;charset=utf-8");

    @include_once("conn.php");

    if(!(isset($_POST["user"])&&isset($_POST["gid"])&&isset($_POST["buyNum"]))){
        $obj = array();
        $obj["status"] = false;
        $obj["msg"] = "请传入完整参数";
        $json = json_encode($obj);
        exit($json);
    }

    $user = $_POST["user"];
    $gid = $_POST["gid"];
    $buyNum = $_POST["buyNum"];

    // 加入购物车之前需要 先判断 当前用户 是否 购买过 该商品?
    // 如何判断 买没买过?    => 查询一下 当前用户 是否 购买过 该商品?
    // 有数据    =>   买过    => 更新数量
    // 没有数据  =>   没买过  => 新增 


    // 查询
    $sql = "select * from `shoppingcar` where user = '$user' and gid = '$gid'";

    // 执行mysql语句
    $result = mysqli_query($conn,$sql);
    // print_r($result);

    $obj = array();
    if($result){

        $item = mysqli_fetch_assoc($result);
        if($item){  //有数据  => 更新
            $sql = "update `shoppingcar` set buyNum = buyNum + $buyNum where user = '$user' and gid = '$gid'";
        }else{
             // 没有数据 => 新增
            $sql = "insert into shoppingcar(user,gid,buyNum) values('$user','$gid',$buyNum)";
        }

         // 执行mysql语句
         $result = mysqli_query($conn,$sql);
         // print_r($result);

         if($result){

             $rows = mysqli_affected_rows($conn);

             // echo $rows;
             if($rows>0){ // 新增成功
                 $obj["status"] = true;
                 $obj["msg"] = "加入成功";
             }else{
                 $obj["status"] = false;
                 $obj["msg"] = "加入失败";
             }

         }else{
             $obj["status"] = false;
             $obj["msg"] = "sql语句有误";
             $obj["sql"] = $sql;
         }


    }else{
        $obj["status"] = false;
        $obj["msg"] = "sql语句有误";
        $obj["sql"] = $sql;
    }



    // --------------------------
   

    echo json_encode($obj);

?>